/**************************************************************************************************
 * TITLE:LogFacebook.java
 * PURPOSE:To create facebook login feature in Android 2.2
 *         1)Authorization(Login)
 *         2)Authorization(Logout)
 *         3)Request ('Greet Me' feature)
 * AUTHOR: Manori Thakur
 * DATE: 02/24/2011
 * SOURCE FOR FACEBOOK API:https://github.com/facebook/facebook-android-sdk/
 **************************************************************************************************/

package com.example.android.debuggermenu;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.facebook.android.R;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.Util;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

public class LogFacebook extends Activity {
	private static final String TAG = LogFacebook.class.getSimpleName();
	public static final String APP_ID = "191897934166516";
	
	private Activity act;
    private Handler mHandler;
    private ImageButton mLoginButton,mLogoutButton;
    private Button mGreetButton,mPostButton;
    private TextView mText;
    private Context mContext;
    
    private String perm[]=new String[]{"email","read_stream"};
    private Facebook facebook;
    private AsyncFacebookRunner asyncfbrunner;
        
    
    /**
     * Called when the Activity is first created
     * 1) Sets the view for the activity
     * 2) Inflates the buttons and the text
     * 3) Creates Facebook object with the registered APP ID for this app
     * 4) Attaches button click listeners
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        act=this;
        mHandler=new Handler();
        mContext=this;
        setContentView(R.layout.start);
        mLoginButton = (ImageButton) findViewById(R.id.login);
        mLogoutButton = (ImageButton) findViewById(R.id.logout);
        mText = (TextView) findViewById(R.id.welcometxt);
        mGreetButton = (Button) findViewById(R.id.greetButton);
        mPostButton = (Button) findViewById(R.id.postButton);
        
        
        
        facebook = new Facebook(APP_ID);                
        asyncfbrunner=new AsyncFacebookRunner(facebook);
        
        //Attaching listeners to the buttons when the Activity is created  
        //For Login button
        mLoginButton.setOnClickListener(new View.OnClickListener() {		
        
        		public void onClick(View v) { //Calls the inbuilt facebook sign on dialog
        			facebook.authorize(act,perm,new LoginDialogListener());
        		}
        });
        
        //For Logout button        
        mLogoutButton.setOnClickListener(new View.OnClickListener() {    		
            
    			public void onClick(View v) {    			
    				asyncfbrunner.logout(act.getApplicationContext(), new LogoutRequestListener());
    			}
        });
        
        //For Greet button
        mGreetButton.setOnClickListener(new View.OnClickListener() {
        	
        		public void onClick(View v) {
        			asyncfbrunner.request("me", new GreetListener());
        		}
        });
        
      //For Post button
        mPostButton.setOnClickListener(new View.OnClickListener() {
        	
        		public void onClick(View v) {
        			facebook.authorize(act, 
        	                new String[] {"publish_stream", "read_stream", "offline_access"}, new PostDialogListener());
        		}
        });
        
    }
        
        

    /**
     * Handles the result returned after this Activity
     * Sends the same info to Facebook
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        facebook.authorizeCallback(requestCode, resultCode, data);
    }
    
    
    public ImageButton getLoginButton() {
    	return mLoginButton;
    }
    
    public Button getGreetButton() {
    	return mGreetButton;
    }
    
    public ImageButton getLogoutButton() {
    	return mLogoutButton;
    }
    
    /**
     * A class that implements DialogListener interface of the facebook api
     *
     */
    
    private final class LoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
            mLoginButton.setVisibility(View.INVISIBLE);
            mLogoutButton.setVisibility(View.VISIBLE);
            mGreetButton.setVisibility(facebook.isSessionValid() ?
                    View.VISIBLE :
                    View.INVISIBLE);
            mPostButton.setVisibility(facebook.isSessionValid() ?
                    View.VISIBLE :
                    View.INVISIBLE);
            mText.setText("Welcome to iCrowdApps!");
        }

        public void onFacebookError(FacebookError error) {
            Log.e(TAG,"Facebook error in LoginDialogListener class "+error.getMessage());
        }
        
        public void onError(DialogError error) {
        	Log.e(TAG,"Dialog error in LoginDialogListener class "+error.getMessage());
        }

        public void onCancel() {
            
        }
    }
    
    /**
     * A class that implements RequestListener interface of the facebook api
     *
     */
    
    private final class GreetListener implements RequestListener {
        public void onComplete(final String response, final Object state) {
        	try {
        		JSONObject json = Util.parseJson(response);
                final String name = json.getString("name");
                
                LogFacebook.this.runOnUiThread(new Runnable() {
                    public void run() {
                        mText.setText("Welcome to DeBugger, " + name + "!");
                    }
                });
        	}catch (JSONException e) {
                Log.e(TAG, "JSON Exception in GreetListener "+e.getMessage());
            } catch (FacebookError e) {
                Log.e(TAG, "Facebook Error in GreetListener " + e.getMessage());
            }
        }

		@Override
		public void onIOException(IOException e, Object state) {
			Log.e(TAG,"IOException in GreetListener class "+e.getMessage());			
		}

		@Override
		public void onFileNotFoundException(FileNotFoundException e,
				Object state) {
			Log.e(TAG,"FileNotFoundException in GreetListener class "+e.getMessage());			
		}

		@Override
		public void onMalformedURLException(MalformedURLException e,
				Object state) {
			Log.e(TAG,"onMalformedURLException in GreetListener class "+e.getMessage());				
		}

		@Override
		public void onFacebookError(FacebookError e, Object state) {
			Log.e(TAG,"Facebook error in GreetListener class "+e.getMessage());
			
		}
    }
    
    
    /**
     * A class that implements RequestListener interface of the facebook api
     *
     */    
    private class LogoutRequestListener implements RequestListener {
        public void onComplete(String response, final Object state) {
            
        	mHandler.post(new Runnable() {
			    public void run() {
			        mLoginButton.setVisibility(View.VISIBLE);
			        mLogoutButton.setVisibility(View.INVISIBLE);
			        mGreetButton.setVisibility(View.INVISIBLE);
			        mText.setText("You have been logged out!"+"\n"+"Please login again");
			    }
			});
        }

		@Override
		public void onIOException(IOException e, Object state) {
			Log.e(TAG,"IOException in LogoutRequestListener class "+e.getMessage());			
		}

		@Override
		public void onFileNotFoundException(FileNotFoundException e,
				Object state) {
			Log.e(TAG,"onFileNotFoundException in LogoutRequestListener class "+e.getMessage());
			
		}

		@Override
		public void onMalformedURLException(MalformedURLException e,
				Object state) {
			Log.e(TAG,"onMalformedURLException in LogoutRequestListener class "+e.getMessage());
			
		}

		@Override
		public void onFacebookError(FacebookError e, Object state) {
			Log.e(TAG,"Facebook error in LogoutRequestListener class "+e.getMessage());			
		}
    }
    
    private final class PostDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
        	if (values.isEmpty())
            {
        		return;
            }
            if (!values.containsKey("post_id"))
            {
                try
                {
                    Bundle parameters = new Bundle();
                    parameters.putString("message", " I played DeBugger :)");// the message to post to the wall
                    facebook.dialog(mContext, "stream.publish", parameters, this);// "stream.publish" is an API call
                }
                catch (Exception e)
                {
                    // TODO: handle exception
                    System.out.println(e.getMessage());
                }
            }

        }

        public void onFacebookError(FacebookError error) {
            Log.e(TAG,"Facebook error in PostDialogListener class "+error.getMessage());
        }
        
        public void onError(DialogError error) {
        	Log.e(TAG,"Dialog error in PostDialogListener class "+error.getMessage());
        }

        public void onCancel() {
            
        }
    }
    

}
    
    
    

    
    
    
   




